/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.lesson.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.klass.entity.EduKlass;
import vip.xiaonuo.biz.modular.klass.service.EduKlassService;
import vip.xiaonuo.biz.modular.lecture.entity.EduLecture;
import vip.xiaonuo.biz.modular.lecture.enums.EduLectureStateEnum;
import vip.xiaonuo.biz.modular.lecture.service.EduLectureService;
import vip.xiaonuo.biz.modular.lesson.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.lesson.entity.EduLesson;
import vip.xiaonuo.biz.modular.lesson.mapper.EduLessonMapper;
import vip.xiaonuo.biz.modular.lesson.service.EduLessonService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 排课Service接口实现类
 *
 * @author liye
 * @date  2023/08/06 10:18
 **/
@Service
public class EduLessonServiceImpl extends ServiceImpl<EduLessonMapper, EduLesson> implements EduLessonService {

    @Autowired
    private TransService transService;

    @Resource
    private EduKlassService eduKlassService;

    @Resource
    private EduLectureService eduLectureService;

    @Override
    public Page<EduLesson> page(EduLessonPageParam eduLessonPageParam) {
        QueryWrapper<EduLesson> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(eduLessonPageParam.getTimeslotId())) {
            queryWrapper.lambda().eq(EduLesson::getTimeslotId, eduLessonPageParam.getTimeslotId());
        }
        if(ObjectUtil.isNotEmpty(eduLessonPageParam.getRoomId())) {
            queryWrapper.lambda().eq(EduLesson::getRoomId, eduLessonPageParam.getRoomId());
        }
        if (ObjectUtil.isNotEmpty(eduLessonPageParam.getTeacher())) {
            queryWrapper.lambda().like(EduLesson::getTeacher, eduLessonPageParam.getTeacher());
        }
        if (ObjectUtil.isNotEmpty(eduLessonPageParam.getSubject())) {
            queryWrapper.lambda().like(EduLesson::getSubject, eduLessonPageParam.getSubject());
        }
        if (ObjectUtil.isNotEmpty(eduLessonPageParam.getStudentGroup())) {
            queryWrapper.lambda().like(EduLesson::getStudentGroup, eduLessonPageParam.getStudentGroup());
        }
        if (ObjectUtil.isNotEmpty(eduLessonPageParam.getLocked())) {
            queryWrapper.lambda().eq(EduLesson::getLocked, eduLessonPageParam.getLocked());
        }
        if(ObjectUtil.isAllNotEmpty(eduLessonPageParam.getSortField(), eduLessonPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(eduLessonPageParam.getSortOrder());
            queryWrapper.orderBy(true, eduLessonPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(eduLessonPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(EduLesson::getId);
        }
        Page<EduLesson> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        List<EduLesson> collect = page.getRecords().stream().collect(Collectors.toList());
        page.setRecords(collect);
        transService.transBatch(page.getRecords());
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EduLessonAddParam eduLessonAddParam) {
        Collection<EduLesson> lessons = new ArrayList<>();
        EduLecture lecture = eduLectureService.getById(eduLessonAddParam.getLectureId());
        transService.transOne(lecture);
        List<String> klassIds = Arrays.stream(lecture.getKlasses().replaceAll("[\\[\\]\"]", "").split(","))
                .map(String::trim) // 去掉空格
                .collect(Collectors.toList());
        List<EduKlass> eduKlasses = eduKlassService.listByIds(klassIds);
        String studentGroup = eduKlasses.stream().map(EduKlass::getName).collect(Collectors.joining(","));
        int classHourPerWeek = (lecture.getClassHour() / (lecture.getToWeek() - lecture.getFromWeek() + 1));
        int classHourPerLesson = eduLessonAddParam.getExtended()? 4: 2;
        for (int i = 0; i < classHourPerWeek; i+=classHourPerLesson) {
            EduLesson lesson = new EduLesson();
            lesson.setLectureId(lecture.getId());
            lesson.setTimeslotId(eduLessonAddParam.getTimeslotId());
            lesson.setRoomId(eduLessonAddParam.getRoomId());
            lesson.setSubject(lecture.getCourseName());
            lesson.setTeacher(lecture.getTeacherName());
            lesson.setStudentGroup(studentGroup);
            lesson.setRoomType(lecture.getRoomType());
            lesson.setLocked(false);
            lesson.setStartWeek(eduLessonAddParam.getStartWeek() == null? lecture.getFromWeek(): eduLessonAddParam.getStartWeek());
            lesson.setEndWeek(eduLessonAddParam.getEndWeek() == null? lecture.getToWeek(): eduLessonAddParam.getEndWeek());
            lesson.setExtended(eduLessonAddParam.getExtended());
            this.save(lesson);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EduLessonEditParam eduLessonEditParam) {
        EduLesson eduLesson = this.queryEntity(eduLessonEditParam.getId());
        BeanUtil.copyProperties(eduLessonEditParam, eduLesson);
        this.updateById(eduLesson);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EduLessonIdParam> eduLessonIdParamList) {
        List<EduLesson> lessons = this.listByIds(CollStreamUtil.toList(eduLessonIdParamList, EduLessonIdParam::getId));
        for (EduLesson lesson: lessons) {
            EduLecture lecture = eduLectureService.getById(lesson.getLectureId());
            lecture.setState(EduLectureStateEnum.DOING.getValue());
            eduLectureService.updateById(lecture);
        }
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(eduLessonIdParamList, EduLessonIdParam::getId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void lock(List<EduLessonIdParam> eduLessonIdParamList) {
        List<EduLesson> lessons = this.listByIds(CollStreamUtil.toList(eduLessonIdParamList, EduLessonIdParam::getId));
        for (EduLesson lesson: lessons) {
            lesson.setLocked(true);
        }
        this.updateBatchById(lessons);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(List<EduLessonIdParam> eduLessonIdParamList) {
        List<EduLesson> lessons = this.listByIds(CollStreamUtil.toList(eduLessonIdParamList, EduLessonIdParam::getId));
        for (EduLesson lesson: lessons) {
            updateBySample(lesson);
        }
    }

    private void updateBySample(EduLesson sample) {
        Map<String, Object> map = new HashMap<>();
        map.put("lecture_id", sample.getLectureId());
        List<EduLesson> lessons = this.listByMap(map);
        for (EduLesson lesson : lessons) {
            lesson.setTimeslotId(sample.getTimeslotId());
            lesson.setRoomId(sample.getRoomId());
            lesson.setTeacher(sample.getTeacher());
        }
        this.updateBatchById(lessons);
    }
    @Override
    public EduLesson detail(EduLessonIdParam eduLessonIdParam) {
        return this.queryEntity(eduLessonIdParam.getId());
    }

    @Override
    public EduLesson queryEntity(String id) {
        EduLesson eduLesson = this.getById(id);
        if(ObjectUtil.isEmpty(eduLesson)) {
            throw new CommonException("排课不存在，id值为：{}", id);
        }
        return eduLesson;
    }
}
